package com.xk857.simpleeffect.activity;

import android.Manifest;
import android.content.ContentValues;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.provider.Settings;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.bumptech.glide.Glide;
import com.google.gson.reflect.TypeToken;
import com.xk857.simpleeffect.R;
import com.xk857.simpleeffect.db.PersonDataBase;
import com.xk857.simpleeffect.domain.Result;
import com.xk857.simpleeffect.domain.entity.Customer;
import com.xk857.simpleeffect.domain.vo.InvitationVo;
import com.xk857.simpleeffect.enums.RequestEnum;
import com.xk857.simpleeffect.utils.OkHttpUtils;
import com.xuexiang.xqrcode.XQRCode;
import com.xuexiang.xui.widget.actionbar.TitleBar;
import com.xuexiang.xui.widget.dialog.materialdialog.MaterialDialog;

import java.io.FileNotFoundException;
import java.io.OutputStream;
import java.lang.reflect.Type;
import java.util.function.Consumer;

import de.hdodenhof.circleimageview.CircleImageView;

public class ShareCodeActivity extends AppCompatActivity {

    private ConstraintLayout constraintLayout5;
    private TextView nickNameText;
    private ImageView codeImgView;
    private CircleImageView headImgView;
    private TitleBar titleBar;
    private ConstraintLayout constraintLayout4;
    private Button downButton;

    private final int REQUEST_CODE_WRITE_EXTERNAL_STORAGE = 4;
    private Bitmap bitmap;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        getWindow().setStatusBarColor(ContextCompat.getColor(this, R.color.white));
        getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        setContentView(R.layout.activity_share_code);
        initView();
        initData();
    }

    private void initData() {
        Customer customer = PersonDataBase.getPersonInfo(this);
        if (customer != null) {
            Glide.with(this).load(customer.getHeadImg()).into(headImgView);
            nickNameText.setText(customer.getNickName());
        }
        Type type = new TypeToken<Result<InvitationVo>>() {
        }.getType();
        OkHttpUtils.getInstance().get(this, RequestEnum.CREATE_FRIEND_SHARE_URL, type, true, (Consumer<InvitationVo>) vo -> {
            runOnUiThread(() -> {
                Bitmap codeBitmap = XQRCode.newQRCodeBuilder(PersonDataBase.ADD_FRIEND_KEY + vo.getUrl()).setSize(480)
                        .setMargin(50)
                        .setWhiteMargin(true)
                        .setBinarize(false)
                        .setDataDotScale(0.8f)
                        .build();
                codeImgView.setImageBitmap(codeBitmap);
            });
        });
    }

    private void initView() {
        constraintLayout5 = findViewById(R.id.constraintLayout5);
        nickNameText = findViewById(R.id.nick_name_text);
        codeImgView = findViewById(R.id.code_img_view);
        headImgView = findViewById(R.id.head_img_view);

        titleBar = findViewById(R.id.title_bar);
        titleBar.setLeftClickListener(v -> finish());

        constraintLayout4 = findViewById(R.id.constraintLayout4);

        downButton = findViewById(R.id.down_button);

        downButton.setOnClickListener(v -> {
            constraintLayout4.setDrawingCacheEnabled(true);
            constraintLayout4.buildDrawingCache();
            bitmap = constraintLayout4.getDrawingCache();
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
                // 已经授予了该权限，可以保存图片
                saveBitmap(bitmap);
            } else {
                // 未授予该权限，需要动态请求授权
                ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CODE_WRITE_EXTERNAL_STORAGE);
            }
        });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_CODE_WRITE_EXTERNAL_STORAGE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // 用户已经授权，可以保存图片
                saveBitmap(bitmap);
            } else {
                // 用户拒绝授权，建议提示用户打开该权限
                new MaterialDialog.Builder(this).iconRes(R.drawable.icon_error_24).title(R.string.error).content("您拒绝了系统写入文件的权限，请前往设置打开权限").positiveText(R.string.yes).onPositive((dialog, which) -> {
                    Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                    intent.setData(Uri.fromParts("package", getPackageName(), null));
                    startActivity(intent);
                }).show();
            }
        }
    }

    private void saveBitmap(Bitmap bitmap) {
        //开始一个新的进程执行保存图片的操作
        Uri insertUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new ContentValues());
        //使用use可以自动关闭流
        try {
            OutputStream outputStream = getContentResolver().openOutputStream(insertUri, "rw");
            if (bitmap.compress(Bitmap.CompressFormat.JPEG, 90, outputStream)) {
                Toast.makeText(this, "保存成功", Toast.LENGTH_SHORT).show();
            } else {
                Toast.makeText(this, "保存失败", Toast.LENGTH_SHORT).show();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            Toast.makeText(this, "保存失败", Toast.LENGTH_SHORT).show();
        }
    }
}